<route lang="yaml">
name: Template
meta:
  layout: default
  menu: true
  title: 用户管理
  icon: Template
  index: 4
</route>
<template>
  <div class="flex-1 min-w-1000px select-none p-16px">
    <el-card class="mb-4">
      <template #header>
        <div class="flex justify-between items-center">
          <span>查询条件</span>
        </div>
      </template>
      <el-form :model="searchForm" inline>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card>
      <template #header>
        <div class="flex justify-between items-center">
          <span>用户列表</span>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </div>
      </template>
      <el-table v-loading="loading" :data="userList" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column
          prop="username"
          label="用户名"
          width="180"
        ></el-table-column>
        <el-table-column prop="avatar" label="头像" width="80">
          <template #default="{ row }">
            <el-image
              v-if="row.avatar"
              :src="row.avatar"
              fit="fill"
              :preview-src-list="[row.avatar]"
            />
            <span v-else>无</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="nickname"
          label="昵称"
          width="180"
        ></el-table-column>
        <el-table-column prop="sex" label="性别" width="180"></el-table-column>
        <el-table-column
          prop="salary"
          label="余额"
          width="180"
        ></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          width="180"
        ></el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div class="mt-4 flex justify-between items-center">
        <el-pagination
          v-model:current-page="searchForm.pageNum"
          v-model:page-size="searchForm.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
  <!-- 编辑弹窗 -->
  <el-dialog
    v-model="dialogVisible"
    title="编辑用户"
    width="500px"
    :before-close="handleClose"
  >
    <el-form :model="editForm" label-width="100px">
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="editForm.username"
          placeholder="请输入用户名"
          :disabled="editForm.id !== null"
        />
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="editForm.nickname" placeholder="请输入昵称" />
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-input v-model="editForm.sex" placeholder="请输入昵称" />
      </el-form-item>
      <el-form-item label="余额" prop="salary">
        <el-input
          v-model="editForm.salary"
          placeholder="请输入余额"
          type="number"
        />
      </el-form-item>
      <el-form-item label="头像">
        <el-input v-model="editForm.avatar" placeholder="请输入头像URL" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSave">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import request from "@/utils/request";

// 搜索表单
const searchForm = reactive<{ pageNum: number; pageSize: number }>({
  pageNum: 1,
  pageSize: 10,
});

// 编辑弹窗相关状态
const dialogVisible = ref(false);
const editForm = reactive<{
  id: number | null;
  username: string;
  nickname: string;
  sex: string;
  salary: string;
  avatar: string;
}>({
  id: null,
  username: "",
  nickname: "",
  sex: "",
  salary: "",
  avatar: "",
});

// 用户列表数据
const userList = ref<any[]>([]);
// 总条数
const total = ref(0);
// 加载状态
const loading = ref(false);

// 生命周期钩子，页面加载时获取数据
onMounted(() => {
  getUserList();
});

// 获取用户列表
const getUserList = async () => {
  loading.value = true;
  try {
    let res: any = await request.get("/admin/template/list", {
      params: searchForm,
    });

    if (res.code === 200) {
      userList.value = res.data.data;
      total.value = res.data.total;
    } else {
      ElMessage.error(res.msg || "获取用户列表失败");
    }
  } catch (error) {
    ElMessage.error("网络异常，请重试");
    console.error("Get admin list error:", error);
  } finally {
    loading.value = false;
  }
};

// 处理搜索
const handleSearch = () => {
  searchForm.pageNum = 1;
  getUserList();
};

// 重置表单
const resetForm = () => {
  searchForm.pageNum = 1;
  searchForm.pageSize = 10;
  getUserList();
};

// 分页大小改变
const handleSizeChange = (size: number) => {
  searchForm.pageSize = size;
  getUserList();
};

// 当前页码改变
const handleCurrentChange = (current: number) => {
  searchForm.pageNum = current;
  getUserList();
};

// 处理状态改变
const handleStatusChange = async (row: any) => {
  // 这里可以实现状态变更的逻辑
  let res: any = await request.post("/admin/template/changeStatus", {
    id: row.id,
    status: row.status,
  });

  if (res.code === 200) {
    ElMessage.success(`已更新ID为${row.id}的用户状态`);
  } else {
    ElMessage.error(res.msg || "更新用户状态失败");
  }
};

// 处理新增
const handleAdd = () => {
  // 重置表单
  editForm.id = null;
  editForm.username = "";
  editForm.nickname = "";

  editForm.sex = "";
  editForm.salary = "";
  editForm.avatar = "";
  // 显示弹窗
  dialogVisible.value = true;
};

// 打开编辑弹窗
const handleEdit = (row: any) => {
  // 复制数据到编辑表单
  editForm.id = row.id;
  editForm.username = row.username;
  editForm.nickname = row.nickname;

  editForm.sex = row.sex;
  editForm.salary = row.salary;
  editForm.avatar = row.avatar;
  // 显示弹窗
  dialogVisible.value = true;
};

// 关闭编辑弹窗
const handleClose = () => {
  dialogVisible.value = false;
  // 重置表单
  editForm.id = null;
  editForm.username = "";
  editForm.nickname = "";

  editForm.sex = "";
  editForm.salary = "";
  editForm.avatar = "";
};

// 保存编辑内容
const handleSave = async () => {
  try {
    let res: any;
    if (editForm.id === null) {
      // 新增
      res = await request.post("/admin/template/add", editForm);
    } else {
      // 编辑
      res = await request.post("/admin/template/edit", editForm);
    }

    if (res.code === 200) {
      ElMessage.success(res.msg || "操作成功");
      handleClose();
      getUserList();
    } else {
      ElMessage.error(res.msg || "操作失败");
    }
  } catch (error) {
    ElMessage.error("网络异常，请重试");
    console.error("Save admin error:", error);
  }
};

// 处理删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm("确定要删除该用户吗？", "删除确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const res: any = await request.post("/admin/template/remove", {
          id: row.id,
        });
        if (res.code === 200) {
          ElMessage.success("删除成功");
          getUserList();
        } else {
          ElMessage.error(res.msg || "删除失败");
        }
      } catch (error) {
        ElMessage.error("网络异常，请重试");
        console.error("Delete admin error:", error);
      }
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};
</script>
